template <typename T>
class UnionFindSet
{
public:
    UnionFindSet()
    {
    }

    template <typename TContainer>
    UnionFindSet(const TContainer &container)
    {
        auto begin = container.begin();
        auto end = container.end();
        while (begin != end)
        {
            m[*begin] = *begin;
            ++begin;
            ++_groupCount;
        }
    }

    void insert(const T &value)
    {
        if (!m.count(value))
        {
            m[value] = value;
            ++_groupCount;
        }
    }

    bool exist(const T &value)
    {
        return m.count(value);
    }

    T find(const T &value)
    {
        if (m[value] == value)
        {
            return value;
        }
        return m[value] = find(m[value]);
    }

    void join(const T &value1, const T &value2)
    {
        if (find(value1) != find(value2))
        {
            m[find(value1)] = find(value2);
            --_groupCount;
        }
    }

    int groupCount()
    {
        return _groupCount;
    }

private:
    std::unordered_map<T, T> m;
    int _groupCount = 0;
};

class Solution
{
public:
    int regionsBySlashes(vector<string> &grid)
    {
        int n = grid.size();
        auto encode = [](int i, int j, int k)
        {
            return (i << 10) + (j << 5) + k;
        };

        UnionFindSet<int> areas;

        for (int i = 0; i < n; ++i)
        {
            for (int j = 0; j < n; ++j)
            {
                for (int k = 0; k < 4; ++k)
                {
                    areas.insert(encode(i, j, k));
                }
            }
        }

        for (int i = 0; i < n; ++i)
        {
            for (int j = 0; j < n; ++j)
            {
                if (i > 0)
                {
                    areas.join(encode(i, j, 0), encode(i - 1, j, 2));
                }
                if (j > 0)
                {
                    areas.join(encode(i, j, 3), encode(i, j - 1, 1));
                }
                switch (grid[i][j])
                {
                case ' ':
                    areas.join(encode(i, j, 0), encode(i, j, 1));
                    areas.join(encode(i, j, 0), encode(i, j, 2));
                    areas.join(encode(i, j, 0), encode(i, j, 3));
                    break;
                case '/':
                    areas.join(encode(i, j, 0), encode(i, j, 3));
                    areas.join(encode(i, j, 1), encode(i, j, 2));
                    break;
                case '\\':
                    areas.join(encode(i, j, 0), encode(i, j, 1));
                    areas.join(encode(i, j, 2), encode(i, j, 3));
                    break;
                default:
                    break;
                }
            }
        }

        return areas.groupCount();
    }
};